#Alexander F. Gazmarariam
#afg2@princeton.edu

library(tidyverse)
library(modelsummary)
library(survey)
library(kableExtra)

source("code/fun/book_theme.r")
source("code/fun/savefig.r")
source("code/fun/coefnames4tables.r")
source("code/fun/fix_txt.r")

#load data
g <- readRDS("data/NatCAPS_20221013.rds")

#specify baseline model
f.base <- y ~ age + Female + Black + Hispanic + CollegeDegree + PartySummary + Income + employfull + rural

#setup table names
coefnames <- c(coefnames, "prior_treat" = "Prior training treatment")

#specify survey weights
g.svy <- svydesign(id = ~ResponseId, weights = ~nweightWeightNEWNL33D_dupe1, data = g)

# Effectiveness of prior assistance ----
prior.ols <- list()
#scale outcome
prior.ols[[1]] <- lm(update(f.base, effective_scale ~ . + prior_treat), g)
prior.ols[[2]] <- lm(update(f.base, effective_scale ~ . + prior_treat + I(age^2)), g)
prior.ols[[3]] <- lm(update(f.base, effective_scale ~ . + prior_treat + I(age^2) + region9 + CollegeDegree * PartySummary), g)
#binary outcome
prior.ols[[4]] <- lm(update(f.base, effective_bin ~ . + prior_treat), g)
prior.ols[[5]] <- lm(update(f.base, effective_bin ~ . + prior_treat + I(age^2)), g)
prior.ols[[6]] <- lm(update(f.base, effective_bin ~ . + prior_treat + I(age^2) + region9 + CollegeDegree * PartySummary), g)
#create table
file <- "tables/ch6/ols_priortraining.txt"
modelsummary(
  prior.ols,
  vcov = "HC2",
  stars = c("*"=.1,"**"=.05,"***"=.01),
  coef_map = coefnames,
  gof_map = c("nobs", "adj.r.squared"),
  escape=FALSE,
  output="latex"
) %>%
  add_header_above(c(" " = 1, "Scale" = 3, "Binary" = 3)) %>%
  cat(., file = file)
fix_txt(file)
